package main

import (
    "fmt"
    "log"
    "net"
    "time"

    pb "example.com/http-grpc-server/proto/hello" // 引入编译生成的包

    hg "example.com/http-grpc-server/handler"

    "golang.org/x/net/context"
    "google.golang.org/grpc"
)

const (
    // Address gRPC服务地址
    Address = "127.0.0.1:50052"
)

// 定义helloService并实现约定的接口
type helloService struct{}

// HelloService Hello服务
var HelloService = helloService{}

/**
* @Description: 实现Hello服务接口
* @Author: liangan
* @Date: 2023-09-02_10:25
*/
func (h helloService) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloResponse, error) {
    resp := new(pb.HelloResponse)
    //resp.Message = fmt.Sprintf("Hello %s.", req.Name)
    log.Printf("接收到客户端的消息: %v", req.GetName())
    time.Sleep(time.Second)
    timeUnix := time.Now().Unix()
    formatTimeStr := time.Unix(timeUnix,0).Format("2006-01-02 15:04:05")
    ms := fmt.Sprintf("好的收到,%s %s", req.GetName(), formatTimeStr)
    log.Printf("回复客户端的消息: %s", ms)
    resp.Message = ms
    return resp, nil
}

/**
* @Description: 普通grpc服务端
* @Author: liangan
* @Date: 2023-09-02_10:15
 */
func main() {
    listen, err := net.Listen("tcp", Address)
    if err != nil {
        log.Printf("failed to listen: %v", err)
    }

    // 创建一个grpc Server服务对象,Handler非必传
    //s := grpc.NewServer() // 可以直接创建对象
    s := grpc.NewServer(grpc.StatsHandler(&hg.MyHandler{}))

    // 注册HelloService
    pb.RegisterHelloServer(s, HelloService)

    // 启动RPC并监听
    log.Printf("server listening at %v", listen.Addr())
    if err := s.Serve(listen); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}

